<?php
class Utils
{

	/**
	 * Get the complete request URL
	 * 
	 * @return  string the URL
	 */
	static function getRequestURL() {
		$protocal = explode('/', $_SERVER['SERVER_PROTOCOL']);
		$protocal = strtolower( $protocal[0]).'://';
		$port =  $_SERVER['SERVER_PORT'];
		$host = $_SERVER['HTTP_HOST'].(strcasecmp('80',$port)==0?'':":$port");
		return $protocal.$host.$_SERVER['REQUEST_URI'];
	}
	/**
	 * End current script and redirect to specified URL
	 * 
	 * @param  string $url, the redirect URL
	 * @param  bool $die, whether die the page after setting the header
	 * @return  bool, false if the headers are already sent, otherwise true
	 */
	static function redirect($url, $die = false, $dieMsg = '') {
		if (!headers_sent()) {
			header('Location: '.$url);
			if ($die)
				die($dieMsg);
			return true;
		}
		return false;
	}
	/**
	 * Build a url string
	 * @param  string $base, the base url
	 * @param  array $params, an associative array containing key/value pairs
	 * @param  bool $encode, whether to urlencode the key/value pairs
	 * @return  the url string
	 */
	static function buildUrl($base, $params = null, $encode = false)
	{
		$url = $base;
		if ($params != null && count($params) > 0) {
			$url .= '?';
			foreach ($params as $key => $value) {
				if ($encode) {
					$key = urlencode($key);
					$value = urlencode($value);
				}
				$url .= ("$key=$value&");
			}
		}
		return $url;
	}
	/**
	 * the function generates a GUID
	 * @return  string the GUID
	 */
	static function guid(){
	   if (function_exists('com_create_guid')){
	       return com_create_guid();
	   }else{
	       mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
	       $charid = strtoupper(md5(uniqid(rand(), true)));
	       $hyphen = chr(45);// "-"
	       $uuid = chr(123)// "{"
	               .substr($charid, 0, 8).$hyphen
	               .substr($charid, 8, 4).$hyphen
	               .substr($charid,12, 4).$hyphen
	               .substr($charid,16, 4).$hyphen
	               .substr($charid,20,12)
	               .chr(125);// "}"
	       return $uuid;
	   }
	}
	
		static function getTimeStamp($datePattern){
			$timeStamp = time();
		if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $datePattern, $regs)) {
			if(ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})[[:space:]]+([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $datePattern, $regs)){
				
				$dateTimeStamp = mktime(intval($regs[4]),intval($regs[5]),intval($regs[6]),intval($regs[2]),intval($regs[3]),intval($regs[1]));
				return $dateTimeStamp;
			}else{
				$dateTimeStamp = mktime(0,0,0,intval($regs[2]),intval($regs[3]),intval($reg[1])) + $timeStamp%(86400) + 28800;
				return $dateTimeStamp;
			}
			
			//get the timestamp of  specified date current time
			//two unix timestamp, so 28800 seconds(8 hours) is less.
			
		}else {
			return $timeStamp;
		}
	}
}
?>